import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';
import 'package:sil_utils_package/tools/SilTools.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

import '../../../api/R.dart';
import '../../../api/request/PowerStationRequest.dart';
import '../../../bloc/userbloc/user_bloc.dart';
import '../../../common/interfaceInstance/FutureBuilderInterfaceInstance.dart';
import '../../../utils/color/ColorUtils.dart';
import '../../Mine/Language/SilLocalizations/SilLocalizations.dart';

class PsDetailSocChartView extends StatefulWidget {
  const PsDetailSocChartView({super.key});

  @override
  State<PsDetailSocChartView> createState() => _PsDetailSocChartViewState();
}

class _PsDetailSocChartViewState extends State<PsDetailSocChartView>
    with FutureBuilderInterfaceInstance {
  List<_SalesData> _data = [];

  TooltipBehavior _tooltipBehavior = TooltipBehavior(
      enable: true, shared: true, activationMode: ActivationMode.singleTap);
  late ZoomPanBehavior _zoomPanBehavior;
  late GlobalKey<State> _globalKey;

  dynamic _future;
  RefreshController _refreshController = RefreshController();

  @override
  void initState() {
    super.initState();
    _future = getData();

    _zoomPanBehavior = ZoomPanBehavior(
        enablePanning: true,
        zoomMode: ZoomMode.x,
        enableDoubleTapZooming: true);
    _globalKey = GlobalKey<State>();
  }

  getData() async {
    String? powerRecordId = UserBlocTool.userEntity?.powerRecordId;
    if (SilTools.stringIsEmpty(powerRecordId)) {
      return;
    }

    R r = await api_power_station_soc_chart(deviceId: powerRecordId!);
    return r.data;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 20.w),
      child: contentView(),
    );
  }

  contentView() {
    return Column(
      children: [
        /// 标题
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SilImage(
              'imgs/home/home_xt.png',
              height: 25.w,
              width: 25.w,
              margin: EdgeInsets.only(right: 2.w),
            ),
            Expanded(
                child: SilText(
              LangOf(context)?.dz_zzw?.soc,
              fontSize: 16.sp,
              maxLines: 0,
              color: ColorUtils.color_font_main,
            ))
            // Expanded(
            //   flex: 1,
            //   child: SilButton(
            //   useConstrained: true,
            //   imgPath: 'imgs/home/home_xt.png',
            //   imgHeight: 25.w,
            //   imgWidth: 25.w,
            //   title: LangOf(context)?.dz_zzw?.soc,
            //   titleColor: ColorUtils.color_font_main,
            //   fontSize: 17.sp,
            //   imagePosition: ImagePosition.Left,
            //   maxLines: 0,
            // )),
            // Expanded(child: Container(),flex: 1,)
          ],
        ),

        /// SOC
        chartFutureView(),
      ],
    );
  }

  chartFutureView() {
    return Container(
        width: 400.w,
        height: 320.w,
        child: SilFutureBuilderWidget(
            key: _globalKey,
            refreshController: _refreshController,
            future: _future,
            mainWidget: (data) {
              handlerData(data);
              return chartWidget();
            },
            reloadFunc: () {
              _future = getData();
              setState(() {});
            },
            interface: this));
  }

  handlerData(Map data) {
    if (SilTools.mapIsEmpty(data)) {
      return;
    }
    _data = [];
    List categories = data['categories'];
    List series = data['series'];

    for (var i = 0; i < series.length; i++) {
      _data.add(
        _SalesData(categories[i], double.parse(series[i])),
      );
    }
  }

  chartWidget() {
    return Container(
        width: 400.w,
        height: 300.w,
        child: SfCartesianChart(
            backgroundColor: Colors.black,
            primaryXAxis: CategoryAxis(
              borderWidth: 0,
              borderColor: Colors.transparent,
              autoScrollingDelta: 6,
              autoScrollingMode: AutoScrollingMode.start,
              interval: 1,

              /// 不显示主轴上的网格线
              majorGridLines: MajorGridLines(
                  width: 0.5, color: ColorUtils.color_subtitle), // 网格线
              majorTickLines: MajorTickLines(width: 0), // 标记线
              axisLine:
                  AxisLine(width: 1, color: ColorUtils.color_font_main), // 轴线
            ),
            primaryYAxis: NumericAxis(
              maximum: 100,
              interval: 20,
              minimum: 0,

              /// 不显示主轴上的网格线
              majorGridLines: MajorGridLines(
                  width: 0.5, color: ColorUtils.color_subtitle), // 网格线
              majorTickLines: MajorTickLines(width: 0), // 标记线
              axisLine:
                  AxisLine(width: 1, color: ColorUtils.color_font_main), // 轴线
            ),
            // 标题
            title: ChartTitle(
                text: ' % ',
                alignment: ChartAlignment.near,
                textStyle: TextStyle(fontSize: 14, shadows: List.empty())),
            // 选中的类型
            selectionType: SelectionType.series,
            // 图示标志
            legend: Legend(
                isVisible: true,
                alignment: ChartAlignment.center,
                position: LegendPosition.bottom,
                textStyle: TextStyle(color: ColorUtils.color_font_main)),
            // Enable tooltip 打开工具提示
            tooltipBehavior: _tooltipBehavior,
            zoomPanBehavior: _zoomPanBehavior,
            series: <ChartSeries<_SalesData, String>>[
              SplineSeries<_SalesData, String>(
                dataSource: _data,
                xValueMapper: (_SalesData sales, _) => sales.year,
                yValueMapper: (_SalesData sales, _) => sales.sales,
                name: 'SOC',
                color: ColorUtils.color_chart_line,
                width: 2,
                animationDuration: 0,
                // 修饰数据点，显示原点
                markerSettings:
                    MarkerSettings(isVisible: true, width: 5, height: 5),
              ),
            ]));
  }
}

class _SalesData {
  _SalesData(this.year, this.sales);

  final String year;
  final double sales;
}
